/**
 * 给定两个整数数组preorder 和 inorder，其中preorder 是二叉树的先序遍历， inorder是同一棵树的中序遍历，请构造二叉树并返回其根节点。
 *https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
 *
 */
class BuildTree {
    public int preorderIndex=0;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder,inorder,0,preorder.length-1);
    }
    public TreeNode buildTreeChild(int[] preorder,int[] inorder,int be,int end){
        if(be>end){
            return null;
        }
        TreeNode root=new TreeNode(preorder[preorderIndex]);
        
        int orderIndex=findOrderRootIndex(inorder,be,end,preorder[preorderIndex]);
        preorderIndex++;
        if(orderIndex==-1){
            return null;
        }
        root.left=buildTreeChild(preorder,inorder,be,orderIndex-1);
        root.right=buildTreeChild(preorder,inorder,orderIndex+1,end);
        return root;

    }
    public int findOrderRootIndex(int[] inorder,int be,int end,int val){
        for(int i=be;i<=end;i++){
            if(inorder[i]==val){
                return i;
            }
        }
        return -1;
    }
}
